###############################################
#
#Compute the neighbors productivity and experience
#IMPORTANT: -DATA NEED TO BE SET BEFORE RUNNING THE FUNCTION
#- NAME THIS DATA SET AS "y"
# Author: Lorenzo Ductor
# First Version: 29/04/2015
#
################################################

netprodg<-function(indi,g,y,endyear){
  nei1 <- V(g)[nei(indi)]
  lnei1 <- sapply(nei1, function(v) list(subset(y,
                           auth2==v|auth1==v|auth3==v|auth4==v|auth5==v|auth6==v|auth7==v)) )
authm<-as.data.frame(do.call("rbind",lnei1))
authmu<-unique(authm)
auth    <- c(2,5,8,11,14,17,20)   # column numbers of months
gender         <- c(3,6,9,12,15,18,21)   # column numbers of Fn
myear<-c(4,7,10,13,16,19,22)
authmul <- reshape(authmu,
             times=colnames(authmu)[auth],
             varying=list(auth,gender,myear),
             v.names=c("auth","gender","myear"),
             direction="long")
authmulx=authmul[,c(1,5,8,10,12,13,14)]
authmulx=authmulx[!duplicated(authmulx), ]
lnei1b <- sapply(nei1, function(v) list(subset(authmulx, auth==v)) )
authmb<-as.data.frame(do.call("rbind",lnei1b))
authmub<-unique(authmb)
netprodmale<-sum(authmub$prodd[authmub$gender==0],na.rm=TRUE)
netprodfemale<-sum(authmub$prodd[authmub$gender==1],na.rm=TRUE)
netaismale<-sum(authmub$aisd[authmub$gender==0],na.rm=TRUE)
netaisfemale<-sum(authmub$aisd[authmub$gender==1],na.rm=TRUE)
netprodm<-sum(authmub$prodd[is.na(authmub$gender)])
authmuc<-na.omit(authmub)  
nmaleco=length(unique(authmuc$auth[authmuc$gender==0]))
nfemaleco=length(unique(authmuc$auth[authmuc$gender==1]))
nmco=length(unique(authmub$auth[is.na(authmub$gender)]))
x=numeric(length(authmub$articleid))+1
authmub[ , "papers"] <- x
papersmale=length(authmuc$auth[authmuc$gender==0])
papersfemale=length(authmuc$auth[authmuc$gender==1])
papersm=length(authmub$prod[is.na(authmub$gender)])
t=(endyear-authmub$myear)+1
authmub[ , "t"] <- t
ua=unique(authmub[,c(5,6,9)])
tmale=mean(ua$t[ua$gender==0],na.rm=TRUE)
tfemale=mean(ua$t[ua$gender==1],na.rm=TRUE)
tm=mean(ua$t[is.na(ua$gender)],na.rm=TRUE)
netprodg<-c(netprodmale,netprodfemale,netprodm, netaismale, netaisfemale, papersmale, papersfemale, papersm, nmaleco, nfemaleco, nmco, tmale, tfemale,tm)
netprodg
}



